package com.leather.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leather.admin.entity.Permission;
import com.leather.admin.mapper.PermissionMapper;
import com.leather.admin.service.PermissionService;
import com.leather.admin.vo.PermissionVo;
import com.leather.common.result.CodeMsg;
import com.leather.common.result.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Override
    public Result addPermission(PermissionVo permissionVo) {
        Result result = permissionVo.validate();
        if (!result.isSuccess()) {
            return result;
        }
        Permission permission = (Permission) result.getData();
        if (null != getPermissionByName(permission.getPermissionName())) {
            return Result.error(CodeMsg.DUPPY_PERMISSIONNAME);
        }
        if (save(permission)) {
            return result;
        }
        return Result.error(CodeMsg.SERVER_ERROR);
    }

    @Override
    public Permission getPermissionByName(String permissionName) {
        if (StringUtils.isBlank(permissionName)) {
            return null;
        }
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("permission_name", permissionName);
        return getOne(queryWrapper);
    }

    @Override
    public IPage<Permission> getAllPermission(Page<Permission> page, String sort, String search) {
        boolean flag = false;
        if (StringUtils.isNotBlank(sort)) {
            if (sort.equals("asc")) {
                flag = true;
            } else {
                flag = false;
            }
        }
        if (StringUtils.isNotBlank(search)) {
            return query().like("permission_name", search).or().like("permission_value", search).orderBy(true, flag, "id").page(page);
        }
        return query().orderBy(true, flag, "id").page(page);
    }

    @Override
    public List<Permission> getParent() {
        return query().eq("is_parent", 0).list();
    }

    @Override
    public Result updatePermission(PermissionVo permissionVo) {
        Result result = permissionVo.validate();
        if (!result.isSuccess()) {
            return result;
        }
        Permission p = (Permission) result.getData();
        if (updateById(p)) {
            return Result.success("success");
        }
        return Result.error(CodeMsg.SERVER_ERROR);
    }
}
